package com.icedevcloud.common.core.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.icedevcloud.common.core.api.R;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * BaseResponseAdvice
 * 定义统一返回处理
 * </p>
 *
 * @author XiaoBingBy
 * @since 2022-03-15
 */
@ControllerAdvice
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {

    private List<String> KNIFE4J_URI = Arrays.asList(
            "/doc.html",
            "/webjars/**",
            "/v3/api-docs/default",
            "/v3/api-docs/swagger-config",
            "/v3/api-docs"
    );

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof R) {
            return body;
        } else if (body instanceof String) {
            HttpHeaders headers = response.getHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(R.ok(body));
        } else if (body == null) {
            return R.ok(null);
        } else if (isKnife4jUrl(request.getURI().getPath())) {
            return body;
        }
        return R.ok(body);
    }

    private boolean isKnife4jUrl(String uri) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String s : KNIFE4J_URI) {
            if (pathMatcher.match(s, uri)) {
                return true;
            }
        }
        return false;
    }

}
